﻿using Opc.Ua.Client;
using Opc.Ua;

partial class Program
{


    static async Task OpcUaClientTest(IServiceProvider serviceProvider)
    {
        try
        {
            // Application configuration
            var config = new ApplicationConfiguration
            {
                ApplicationName = "OPC UA Client",
                ApplicationType = ApplicationType.Client,
                SecurityConfiguration = new SecurityConfiguration
                {
                    ApplicationCertificate = new CertificateIdentifier(),
                    AutoAcceptUntrustedCertificates = true,
                    RejectSHA1SignedCertificates = false
                },
                TransportConfigurations = new TransportConfigurationCollection(),
                TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
                ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }
            };

            await config.Validate(ApplicationType.Client);

            // Create a session
            var endpointURL = "opc.tcp://127.0.0.1:49320"; // Replace with your server's endpoint
            var endpoint = CoreClientUtils.SelectEndpoint(endpointURL, useSecurity: false);
            //var identity = new UserIdentity("administrator", "123456");
            IUserIdentity? identity = null;
            var session = Session.Create(config, new ConfiguredEndpoint(null, endpoint, EndpointConfiguration.Create(config)), false, "OPC UA Client", 60000, identity, null).Result;

            Console.WriteLine("Connected to OPC UA server.");

            // Read a node value
            var nodeId = new NodeId("ns=2;s=模拟器示例.函数.Random1"); // Replace with your node ID
            var value = session.ReadValue(nodeId);
            Console.WriteLine($"Value of node {nodeId}: {value.Value}");

            // Close the session
            session.Close();
            Console.WriteLine("Session closed.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }

    }
}
